/**
 * 任务状态工具函数
 * 提供状态转换、验证和业务逻辑处理功能
 */

import { 
  TASK_STATUS, 
  APPLICANT_STATUS, 
  PUBLISHER_STATUS, 
  USER_ROLE,
  getStatusConfig,
  getAvailableActions,
  type TaskStatus,
  type ApplicantStatus,
  type PublisherStatus,
  type UserRole,
  type ActionType
} from "@/constants/taskStatus";

/**
 * 验证状态转换是否合法
 * @param fromStatus - 当前状态
 * @param toStatus - 目标状态
 * @param statusType - 状态类型 ('task', 'applicant', 'publisher')
 * @returns 是否允许转换
 */
export const isValidStatusTransition = (fromStatus: number, toStatus: number, statusType: 'task' | 'applicant' | 'publisher' = 'task'): boolean => {
  const validTransitions: Record<string, Record<number, number[]>> = {
    task: {
      [TASK_STATUS.PAID]: [TASK_STATUS.IN_PROGRESS, TASK_STATUS.CANCELLED, TASK_STATUS.DISPUTED],
      [TASK_STATUS.IN_PROGRESS]: [TASK_STATUS.COMPLETED, TASK_STATUS.DISPUTED],
      [TASK_STATUS.CANCELLED]: [],
      [TASK_STATUS.COMPLETED]: [],
      [TASK_STATUS.DISPUTED]: [TASK_STATUS.COMPLETED, TASK_STATUS.CANCELLED],
    },
    applicant: {
      [APPLICANT_STATUS.APPLIED]: [APPLICANT_STATUS.SELECTED, APPLICANT_STATUS.REJECTED],
      [APPLICANT_STATUS.SELECTED]: [APPLICANT_STATUS.WORKING, APPLICANT_STATUS.DISPUTED],
      [APPLICANT_STATUS.REJECTED]: [],
      [APPLICANT_STATUS.WORKING]: [APPLICANT_STATUS.SUBMITTED, APPLICANT_STATUS.DISPUTED],
      [APPLICANT_STATUS.SUBMITTED]: [APPLICANT_STATUS.DISPUTED],
      [APPLICANT_STATUS.DISPUTED]: [APPLICANT_STATUS.WORKING, APPLICANT_STATUS.SUBMITTED],
    },
    publisher: {
      [PUBLISHER_STATUS.PUBLISHED]: [PUBLISHER_STATUS.CONFIRMED, PUBLISHER_STATUS.DISPUTED],
      [PUBLISHER_STATUS.CONFIRMED]: [PUBLISHER_STATUS.SETTLED, PUBLISHER_STATUS.DISPUTED],
      [PUBLISHER_STATUS.SETTLED]: [],
      [PUBLISHER_STATUS.DISPUTED]: [PUBLISHER_STATUS.SETTLED],
    },
  };

  const transitions = validTransitions[statusType];
  return transitions[fromStatus]?.includes(toStatus) || false;
};

/**
 * 获取状态转换的下一步可能状态
 * @param currentStatus - 当前状态
 * @param statusType - 状态类型
 * @returns 可能的下一步状态列表
 */
export const getNextPossibleStatuses = (currentStatus: number, statusType: 'task' | 'applicant' | 'publisher' = 'task'): number[] => {
  const validTransitions: Record<string, Record<number, number[]>> = {
    task: {
      [TASK_STATUS.PAID]: [TASK_STATUS.IN_PROGRESS, TASK_STATUS.CANCELLED, TASK_STATUS.DISPUTED],
      [TASK_STATUS.IN_PROGRESS]: [TASK_STATUS.COMPLETED, TASK_STATUS.DISPUTED],
      [TASK_STATUS.CANCELLED]: [],
      [TASK_STATUS.COMPLETED]: [],
      [TASK_STATUS.DISPUTED]: [TASK_STATUS.COMPLETED, TASK_STATUS.CANCELLED],
    },
    applicant: {
      [APPLICANT_STATUS.APPLIED]: [APPLICANT_STATUS.SELECTED, APPLICANT_STATUS.REJECTED],
      [APPLICANT_STATUS.SELECTED]: [APPLICANT_STATUS.WORKING, APPLICANT_STATUS.DISPUTED],
      [APPLICANT_STATUS.REJECTED]: [],
      [APPLICANT_STATUS.WORKING]: [APPLICANT_STATUS.SUBMITTED, APPLICANT_STATUS.DISPUTED],
      [APPLICANT_STATUS.SUBMITTED]: [APPLICANT_STATUS.DISPUTED],
      [APPLICANT_STATUS.DISPUTED]: [APPLICANT_STATUS.WORKING, APPLICANT_STATUS.SUBMITTED],
    },
    publisher: {
      [PUBLISHER_STATUS.PUBLISHED]: [PUBLISHER_STATUS.CONFIRMED, PUBLISHER_STATUS.DISPUTED],
      [PUBLISHER_STATUS.CONFIRMED]: [PUBLISHER_STATUS.SETTLED, PUBLISHER_STATUS.DISPUTED],
      [PUBLISHER_STATUS.SETTLED]: [],
      [PUBLISHER_STATUS.DISPUTED]: [PUBLISHER_STATUS.SETTLED],
    },
  };

  return validTransitions[statusType][currentStatus] || [];
};

/**
 * 检查任务是否可以执行特定操作
 * @param task - 任务对象
 * @param actionType - 操作类型
 * @param userRole - 用户角色
 * @returns 是否可以执行操作
 */
export const canPerformAction = (task: { taskStatus?: number; status?: string; userStatus?: number }, actionType: ActionType, userRole: UserRole): boolean => {
  const availableActions = getAvailableActions(
    task.taskStatus || 0,
    userRole,
    task.userStatus
  );
  return availableActions.includes(actionType);
};

/**
 * 获取任务的状态描述
 * @param task - 任务对象
 * @param userRole - 用户角色
 * @returns 状态描述
 */
export const getTaskStatusDescription = (task: { taskStatus?: number; status?: string; userStatus?: number }, userRole: UserRole): string => {
  const taskConfig = getStatusConfig(task.taskStatus || 0, 'task');
  if (!taskConfig) return task.status || '未知状态';

  if (userRole === USER_ROLE.PUBLISHER) {
    return `发布方：${taskConfig.label}`;
  } else if (userRole === USER_ROLE.APPLICANT) {
    const userStatusConfig = getStatusConfig(task.userStatus || 0, 'applicant');
    return userStatusConfig ? `接单人：${userStatusConfig.label}` : `任务：${taskConfig.label}`;
  }

  return taskConfig.label;
};

/**
 * 检查任务是否处于最终状态
 * @param status - 状态值
 * @param statusType - 状态类型
 * @returns 是否为最终状态
 */
export const isFinalStatus = (status: number, statusType: 'task' | 'applicant' | 'publisher' = 'task'): boolean => {
  const finalStatuses: Record<string, number[]> = {
    task: [TASK_STATUS.CANCELLED, TASK_STATUS.COMPLETED],
    applicant: [APPLICANT_STATUS.REJECTED, APPLICANT_STATUS.SUBMITTED],
    publisher: [PUBLISHER_STATUS.SETTLED],
  };

  return finalStatuses[statusType]?.includes(status) || false;
};

/**
 * 获取任务的生命周期阶段
 * @param task - 任务对象
 * @returns 生命周期阶段
 */
export const getTaskLifecycleStage = (task: { taskStatus?: number; status?: string }): string => {
  const status = task.taskStatus || 0;
  
  switch (status) {
    case TASK_STATUS.PAID:
      return 'recruitment'; // 招募阶段
    case TASK_STATUS.IN_PROGRESS:
      return 'execution'; // 执行阶段
    case TASK_STATUS.COMPLETED:
      return 'completed'; // 完成阶段
    case TASK_STATUS.CANCELLED:
      return 'cancelled'; // 取消阶段
    case TASK_STATUS.DISPUTED:
      return 'disputed'; // 纠纷阶段
    default:
      return 'unknown';
  }
};

/**
 * 计算任务进度百分比
 * @param task - 任务对象
 * @returns 进度百分比 (0-100)
 */
export const calculateTaskProgress = (task: { taskStatus?: number; status?: string }): number => {
  const stage = getTaskLifecycleStage(task);
  
  const progressMap: Record<string, number> = {
    'recruitment': 25,
    'execution': 75,
    'completed': 100,
    'cancelled': 0,
    'disputed': 50,
    'unknown': 0,
  };

  return progressMap[stage] || 0;
};

/**
 * 获取任务的状态优先级（用于排序）
 * @param status - 状态值
 * @param statusType - 状态类型
 * @returns 优先级数值（越小优先级越高）
 */
export const getStatusPriority = (status: number, statusType: 'task' | 'applicant' | 'publisher' = 'task'): number => {
  const priorityMap: Record<string, Record<number, number>> = {
    task: {
      [TASK_STATUS.DISPUTED]: 1, // 纠纷最高优先级
      [TASK_STATUS.IN_PROGRESS]: 2, // 进行中
      [TASK_STATUS.PAID]: 3, // 已支付
      [TASK_STATUS.COMPLETED]: 4, // 已完成
      [TASK_STATUS.CANCELLED]: 5, // 已取消
    },
    applicant: {
      [APPLICANT_STATUS.DISPUTED]: 1,
      [APPLICANT_STATUS.WORKING]: 2,
      [APPLICANT_STATUS.SELECTED]: 3,
      [APPLICANT_STATUS.APPLIED]: 4,
      [APPLICANT_STATUS.SUBMITTED]: 5,
      [APPLICANT_STATUS.REJECTED]: 6,
    },
    publisher: {
      [PUBLISHER_STATUS.DISPUTED]: 1,
      [PUBLISHER_STATUS.CONFIRMED]: 2,
      [PUBLISHER_STATUS.PUBLISHED]: 3,
      [PUBLISHER_STATUS.SETTLED]: 4,
    },
  };

  return priorityMap[statusType][status] || 999;
};

/**
 * 格式化任务状态显示
 * @param task - 任务对象
 * @param userRole - 用户角色
 * @returns 格式化后的状态信息
 */
export const formatTaskStatus = (task: { taskStatus?: number; status?: string; userStatus?: number }, userRole: UserRole) => {
  const taskConfig = getStatusConfig(task.taskStatus || 0, 'task');
  const userStatusConfig = task.userStatus ? getStatusConfig(task.userStatus, userRole === USER_ROLE.PUBLISHER ? 'publisher' : 'applicant') : null;
  
  return {
    taskStatus: {
      label: taskConfig?.label || task.status,
      color: taskConfig?.color || '#666',
      bgColor: taskConfig?.bgColor || '#f5f5f5',
      borderColor: taskConfig?.borderColor || '#d9d9d9',
    },
    userStatus: userStatusConfig ? {
      label: userStatusConfig.label,
      color: userStatusConfig.color,
      bgColor: userStatusConfig.bgColor,
      borderColor: userStatusConfig.borderColor,
    } : null,
    description: getTaskStatusDescription(task, userRole),
    progress: calculateTaskProgress(task),
    stage: getTaskLifecycleStage(task),
    priority: getStatusPriority(task.taskStatus || 0, 'task'),
  };
};

/**
 * 验证任务数据完整性
 * @param task - 任务对象
 * @returns 验证结果
 */
export const validateTaskData = (task: { id?: number; taskTitle?: string; totalReward?: string; deadline?: string; taskStatus?: number; userStatus?: number; userRole?: UserRole }) => {
  const errors: string[] = [];
  const warnings: string[] = [];

  // 必需字段检查
  if (!task.id) errors.push('任务ID不能为空');
  if (!task.taskTitle) errors.push('任务标题不能为空');
  if (!task.totalReward) errors.push('任务金额不能为空');
  if (!task.deadline) errors.push('截止日期不能为空');

  // 状态一致性检查
  if (task.taskStatus && task.userStatus) {
    const taskConfig = getStatusConfig(task.taskStatus, 'task');
    const userConfig = getStatusConfig(task.userStatus, task.userRole === USER_ROLE.PUBLISHER ? 'publisher' : 'applicant');
    
    if (!taskConfig) warnings.push(`未知的任务状态: ${task.taskStatus}`);
    if (!userConfig) warnings.push(`未知的用户状态: ${task.userStatus}`);
  }

  // 金额格式检查
  if (task.totalReward && isNaN(Number(task.totalReward))) {
    errors.push('任务金额格式不正确');
  }

  // 日期格式检查
  if (task.deadline && !Date.parse(task.deadline)) {
    errors.push('截止日期格式不正确');
  }

  return {
    isValid: errors.length === 0,
    errors,
    warnings,
  };
};

/**
 * 获取任务统计信息
 * @param tasks - 任务列表
 * @param userRole - 用户角色
 * @returns 统计信息
 */
export const getTaskStatistics = (tasks: Array<{ taskStatus?: number; status?: string; totalReward?: string }>, userRole: UserRole) => {
  const stats = {
    total: tasks.length,
    byStatus: {} as Record<number, number>,
    byStage: {} as Record<string, number>,
    totalAmount: 0,
    averageAmount: 0,
  };

  tasks.forEach(task => {
    const status = task.taskStatus || 0;
    const stage = getTaskLifecycleStage(task);
    const amount = Number(task.totalReward) || 0;

    // 按状态统计
    stats.byStatus[status] = (stats.byStatus[status] || 0) + 1;

    // 按阶段统计
    stats.byStage[stage] = (stats.byStage[stage] || 0) + 1;

    // 金额统计
    stats.totalAmount += amount;
  });

  stats.averageAmount = stats.total > 0 ? stats.totalAmount / stats.total : 0;

  return stats;
};
